<template>
    <div>
        <button @click="convertToCsv">json导出为csv</button>
    </div>
</template>

<script>
    import { Parser } from "json2csv";

    export default {
        name: "JsonToCsvView",
        methods: {
            convertToCsv() {
                // 将 JSON 数据存储在变量中，这里使用示例数据
                const jsonData = [
                    { name: "John", age: 30, city: "New York" },
                    { name: "Jane", age: 25, city: "Los Angeles" },
                    { name: "Bob", age: 35, city: "Chicago" }
                ];

                // 定义 CSV 字段，即 JSON 对象的属性名称
                const fields = ["name", "age", "city"];

                // 创建一个新的 JSON-CSV 转换器实例
                const json2csvParser = new Parser({ fields });

                // 将 JSON 数据转换为 CSV 格式
                const csvData = json2csvParser.parse(jsonData);

                // 创建一个虚拟的下载链接
                const downloadLink = document.createElement("a");
                downloadLink.href = "data:text/csv;charset=utf-8," + encodeURI(csvData);
                downloadLink.download = "data.csv";

                // 触发点击事件进行下载
                downloadLink.click();
            }
        }
    }
</script>

<style scoped>

</style>